package com.ca.singlesignon.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * Create By Gary
 */
@Configuration
public class RedisPool {

    @Value("${spring.redis.host}")
    private   String ip;

    @Value("${spring.redis.password}")
    private   String password;

    @Value("${spring.redis.port}")
    private   Integer port;

    @Value("${spring.redis.database}")
    private Integer database;

    @Value("${spring.redis.jedis.pool.max-active}")
    private  Integer maxTotal;//最大连接数

    @Value("${spring.redis.jedis.pool.max-idle}")
    private  Integer maxIdle; //最大空闲实例个数

    @Value("${spring.redis.jedis.pool.min-idle}")
    private  Integer minIdle; //最小空闲实例个数

    private  Boolean testOnBorrow=true;//true 表示得到的实例可用

    private  Boolean testOnReturn=true;//true 表示归还的实例可用


    @Bean(name="jedisPool")
    public JedisPool  jedisPool(){
        JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setBlockWhenExhausted(true);  //连接耗尽时是否阻塞，true阻塞直到超时
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestOnBorrow(testOnReturn);
       return new JedisPool(jedisPoolConfig,ip,port,1000*2,password,database);
    }
    public Jedis getJedis(){
        return jedisPool().getResource();
    }
    public  void returnBrokenResource(Jedis jedis){
       jedisPool().returnBrokenResource(jedis);
    }
    public  void returnResource(Jedis jedis){
       jedisPool().returnResource(jedis);
    }

}
